import { ConfigService } from '@nestjs/config';
import * as https from 'https';
import * as querystring from 'querystring';

const host = 'sms-api.luosimao.com';

/**
 * 发送验证码
 * @param mobile
 * @param code
 * @constructor
 */
export async function SendCode(mobile: string, code: string) {
  const message = `您的验证码是：${code}，5分钟内有效【领绣】`;
  const postData = {
    mobile,
    message,
  };
  const config = new ConfigService();
  const content = querystring.stringify(postData);
  const options = {
    host: host,
    path: '/v1/send.json',
    method: 'POST',
    auth: 'api:key-' + config.get('MESSAGE_KEY'),
    agent: false,
    rejectUnauthorized: false,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': content.length,
    },
  };

  return new Promise((resolve, reject) => {
    const req = https.request(options, function (res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        resolve(JSON.parse(chunk));
      });
      res.on('end', function () {});
    });

    req.write(content);
    req.end();
  });

  // const rep = await axios.post(host + '/v1/send.json', postData, {
  //   auth: {
  //     username: 'api',
  //     password: 'api:key-' + config.get('MESSAGE_KEY'),
  //   },
  // });
}
